package com.luxk.db.tests;

import java.io.File;
import java.io.IOException;
import java.net.URL;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class TestSAXParser {
	
	public static final String XML_PATH = "example.xml";

	public static void main(String[] args) {
		try {
			URL url =
				TestSAXParser.class.getResource(TestSAXParser.XML_PATH);
			System.out.println(url);

			SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
			File f = new File(url.getFile());
			DefaultHandler dh = new NewHandler();
			parser.parse(f, dh);
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

class NewHandler extends DefaultHandler {
	public void startElement(String uri, String localName, String qName,
			Attributes atts) {
		System.out.println("startElement qName: " + qName);
		int len = atts.getLength();
		for(int i = 0; i < len; i++)
			System.out.println("  Attr #" + i +
					" key:" + atts.getQName(i) + ", val:" + atts.getValue(i));
	}

	public void endElement(String uri, String localName, String qName) {
		System.out.println("endElement qName: " + qName);
	}
	
	public void characters(char[] chars, int start, int length) {
		String str = new String(chars, start, length).trim();
		if(str != null && !"".equals(str))
			System.out.println("characters(" + start + ", " + length + "): " +
				str.trim());
	}
}